module GTranslate
  class InvalidIso_639_2  < ArgumentError; end
  class InvalidSourceText < ArgumentError; end

  class Translator
    # Create an instance with the specified options
    # 
    # ==== Parameters
    # text<String>::
    #   The text you want to be translated
    # source<String>::
    #   The source of the language. Currently only iso_639_2 codes are allowed
    #   (2 letter codes i.e. English -> en, German -> de, etc)
    # target<String>::
    #   The target of the language. Same as source, only iso_639_2
    #
    # ==== Returns
    #   GTranslate:: a GTranslate object
    #—
    # @public
    def initialize( text, source, target )
      assert_valid_text! text
      assert_valid_iso_639_2! source, target
      
      @text, @source, @target = text, source, target
    end
  
    # Do the actual translation. 
    # 
    # ===== Returns
    #   String:: the translated text
    #—
    # @public
    def translate
      client.request :text => @text, :source => @source, :target => @target
    end
  
    protected
      def client
        @client ||= GTranslate::Client.new
      end
   
      def assert_valid_text!(*strings)
        strings.each do |string|
          raise InvalidSourceText unless String === string
        end
      end
      
      def assert_valid_iso_639_2!(*args)
        args.each do |code|
          unless code =~ /^[a-z]{2}$/
            raise InvalidIso_639_2, "#{code} is not a valid iso_639_2 code"
          end
        end
      end
  end
end